import { jwtUserName, getJwtToken } from '@/utils/user'

import Vue from 'vue'
import { Message } from 'element-ui'
import Cookies from 'js-cookie'

let messageInstance = null;
const resetMessage = (options) => {
    if(messageInstance) {
        messageInstance.close()
    }
    messageInstance = Message(options)
};
['error','success','info','warning'].forEach(type => {
    resetMessage[type] = options => {
        if(typeof options === 'string') {
            options = {
                message:options
            }
        }
        options.type = type
        return resetMessage(options)
    }
})
export const message = resetMessage

// Vue.prototype.$message = Message

export default {
  state: {
    id: 0,
    realName: '',
    superAdmin: 0,
    // 公司列表
    companyAccountInfo: [],
    defaultCompanyId: localStorage.getItem('defaultCompanyId') || '',
    defaultCompanyName: '请登录',
    defaultCompanyAuthentFlag: '', // 当前企业是否认证认证标识（10 未认证、20 待认证、30 驳回、40 已认证）
    userId: '',
    userName: '',
    name: '',
    sex: '',
    mobile: '',
    email: '',
    code: '',
    zfName: '',
    company: {
      companyName: '浙江新安化工集团股份有限公司'
    },
    idToken: ''
  },
  mutations: {
    defaultCompanyId (state, defaultCompanyId) {
      localStorage.setItem('defaultCompanyId', defaultCompanyId)
      state.defaultCompanyId = defaultCompanyId
    },
    defaultCompanyName (state, defaultCompanyName) {
      // localStorage.setItem('defaultCompanyName', defaultCompanyName)
      state.defaultCompanyName = defaultCompanyName
    },
    defaultCompanyAuthentFlag (state, defaultCompanyAuthentFlag) {
      state.defaultCompanyAuthentFlag = defaultCompanyAuthentFlag
    },
    companyAccountInfo (state, companyAccountInfo) {
      state.companyAccountInfo = companyAccountInfo
    },
    userId (state, userId) {
      localStorage.setItem('userId', userId)
      state.userId = userId
    },
    userName (state, userName) {
      state.userName = userName
    },
    name (state, name) {
      localStorage.setItem('userName', name)
      state.name = name
    },
    mobile (state, mobile) {
      state.mobile = mobile
    },
    email (state, email) {
      state.email = email
    },
    id (state, id) {
      state.id = id
    },
    zfName (state, zfName) {
      state.zfName = zfName
    }
  },
  actions: {
    // zfName({ state, commit }, companyList) {
    //   if (companyList && companyList.length !== 0) {
    //     let com = companyList.find(item => {
    //       return item.companyId === item.defaultCompanyId
    //     })
    //     commit('companyAccountInfo', companyList)
    //     commit('defaultCompanyId', companyList[0].defaultCompanyId)
    //     commit('defaultCompanyName', com.companyName)
    //     commit('defaultCompanyAuthentFlag', com.authentFlag)
    //   } else {
    //     commit('defaultCompanyId', '')
    //     commit('defaultCompanyName', '')
    //     commit('defaultCompanyAuthentFlag', '')
    //     commit('companyAccountInfo', [])
    //   }
    // },
    companyList ({ state, commit }, companyList) {
      if (companyList && companyList.length !== 0) {
        let com = companyList.find(item => {
          return item.companyId === item.defaultCompanyId
        })
        commit('companyAccountInfo', companyList)
        commit('defaultCompanyId', companyList[0].defaultCompanyId)
        commit('defaultCompanyName', com.companyName)
        commit('defaultCompanyAuthentFlag', com.authentFlag)
      } else {
        commit('defaultCompanyId', '')
        commit('defaultCompanyName', '')
        commit('defaultCompanyAuthentFlag', '')
        commit('companyAccountInfo', [])
      }
    },
    setUserInfo ({ state, commit }, userInfo) {
      if (userInfo) {
        commit('userId', userInfo.userId)
        commit('userName', userInfo.userName)
        commit('name', userInfo.name)
        commit('mobile', userInfo.mobile)
        commit('email', userInfo.email)
        commit('id', userInfo.userId)
      }
    },
    loginUser ({ state, commit, dispatch }, { idToken, publicKey }) {
      idToken = idToken || state.idToken
      // paramsOrg = {
      //   appCode: 'PLANTMATE_OFFICIAL',
      //   client_id: 'android',
      //   grant_type: 'password',
      //   loginType: '0',
      //   password: 'Xinanjituan2421',
      //   username: 'xinanjituan'
      // }
      // console.log(paramsOrg, paramsOrg)
      // const Base64 = require('js-base64').Base64
      // let params = Object.assign({}, paramsOrg)
      // params.password = Base64.encode(paramsOrg.password)
      return new Promise((resolve, reject) => {
        jwtUserName({ idToken, publicKey })
          .then(({ data }) => {
            if (data.code === 0) {
              // if (data.data.defaultCompanyId === '' || data.data.defaultCompanyId === null) {
              //   return Vue.prototype.$message.warning('该企业未入驻!')
              // }
              commit('defaultCompanyId', data.data.defaultCompanyId || '')
              commit('userName', data.data.username || '')
              getJwtToken({
                idToken: idToken,
                publicKey: publicKey,
                username: data.data.username
              })
                .then(({ data }) => {
                  if (data.code === 0) {
                    Cookies.set('access_token', data.data.access_token)
                    resolve()
                  } else {
                    reject(data.message)
                  }
                })
            }
          })
          .catch(err => {
            reject(err)
          })
        // loginUser(params)
        //   .then(({ data }) => {
        //     if (data.code === 0) {
        //       Cookies.set('access_token', data.data.access_token)
        //       window.SITE_CONFIG['permissions'] = data.data.permissions || []
        //       resolve()
        //     } else {
        //       reject(data.message)
        //     }
        //   }).catch(err => {
        //     reject(err)
        //   })
      })
    }
  }
}
